package com.imooc.coupon.advice;

import com.imooc.coupon.annotation.IgnoreResponseAdvice;
import com.imooc.coupon.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @description:
 * @author：naxiaozi，微信：naxiaozi
 * @date: 2025/8/7
 * @Copyright：advice增强的意思
 */
@RestControllerAdvice
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {
    /*判断是否对需要对响应进行处理 true 需要处理 false 不需要*/
    @Override
    @SuppressWarnings("all")
    public boolean supports(MethodParameter methodParameter,
                            Class<? extends HttpMessageConverter<?>> aClass) {
        //如果当前的方法所在类标识了 @IgnoreResponseAdvice 注解，不需要处理
        if(methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)){
            return  false;
        }

        //如果当前的方法标识了 @IgnoreResponseAdvice 注解，不需要处理
        if(methodParameter.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)){
            return false;
        }
        return true;
    }

    @Override
    @SuppressWarnings("all")
    //响应之前
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        //定义最终的返回对象
        CommonResponse<Object> response = new CommonResponse<>(
                0,""
        );
        //如果o 是null response 不需要设置data
        if(null==o){
            return response;
            //如果o已经是CommonResponse 不需要再次处理
        }else if (o instanceof CommonResponse){
            response = (CommonResponse<Object>) o;
        }else {
            //否则，把响应对象作为CommonResponse的data部分
            response.setData(o);
        }
        return null;
    }
}
